<template>
	<a-menu
		@click="handleMenuClick"
		:openKeys="expandsKeys"
		v-model:selectedKeys="selectedKeys"
		mode="inline"
		:theme="theme"
		@openChange="onOpenChange"
		class="control-content app-control-menu__content"
	>
		<template v-for="item in menus" :key="item.name">
			<slot
				v-if="hasSlot(item.name)"
				:item="item" 
				:counterData="props.counterData"
				:name="item.name"
				>
			</slot>
			<slot
				v-else-if="hasSlot('MenuBody')"
				:item="item" 
				:counterData="props.counterData"
				name="MenuBody">
			</slot>
			<AppMenuitem v-else :item="item" :counterData="props.counterData"></AppMenuitem>
		</template>
	</a-menu>
</template>
<script lang="ts" setup>
import AppMenuitem from './menu-item.vue';
import { MenuProps } from '../menu';
import { IParam, IProjectSetting } from '@/core';
const props = defineProps(MenuProps);
const emit = defineEmits(['menuClick']);

const selectedKeys = ref<string[]>([]);

const expandsKeys = ref<string[]>([]);

const projectSetting: IProjectSetting = App.getProjectSetting();

const handleMenuClick = ({ key }: any): void => {
	emit('menuClick', key);
};

const hasSlot = (name: string): boolean => {
	return !!useSlots()[name];
};

watch(
	() => props.selections,
	() => {
		selectedKeys.value = props.selections;
	},
	{ immediate: true }
);

watch(
	() => props.defaultExpands,
	() => {
		expandsKeys.value = props.defaultExpands;
	},
	{ immediate: true }
);

// 设置默认图标
onMounted(() => {
	props.menus.forEach((item: IParam) => {
		if (!item.imgPath && !item.iconClass) {
			item.iconClass = 'fa fa-cogs';
		}
	});
});

const theme = projectSetting.menuSetting.theme.toLowerCase();

const accordion = projectSetting.menuSetting.accordion;

const onOpenChange = (openKeys: string[]) => {
	if (accordion) {
		const latestOpenKey = openKeys.find(
			(key) => expandsKeys.value.indexOf(key) === -1
		);
		const index = props.menus.findIndex((menu: any) =>
			Object.is(menu.name, latestOpenKey)
		);
		if (index === -1) {
			expandsKeys.value = openKeys;
		} else {
			expandsKeys.value = latestOpenKey ? [latestOpenKey] : [];
		}
	}
};
</script>